#! /bin/sh

#安装失败
function installfail()
{
	echo "产品包安装失败，请联系北塔总部获取帮助！"
	exit 1
}
# 校验返回值
function validateResult()
{
	echo $(date "+%Y-%m-%d %H:%M:%S")" "$2" result: "$1   >> $installdir/install.log
	if [[ -z "$1" ]]; then
		echo $(date "+%Y-%m-%d %H:%M:%S")" $2 失败... "  >> $installdir/install.log
		#杀死当前脚本运行的进程 $$为当前脚本运行的进程ID
		installfail
	fi
	#local code=200
	local state=`echo $1 | grep -Po "\"code\"\\s*:\\s*\K[\\d]+"`
	local msg=`echo $1 | grep -Po "\"msg\"\\s*:\\s*\"\K[^\"]+"`
	if [[ 200 -ne $state ]]
	then
		echo $(date "+%Y-%m-%d %H:%M:%S")" $2 失败... $msg "  >> $installdir/install.log
		installfail
	else
		echo $(date "+%Y-%m-%d %H:%M:%S")" $2 成功! "  >> $installdir/install.log
	fi
}

# 检查app是否已经安装完
function validateAppInstall()
{
	local name=`echo $4 | awk -F "_" '{print $1}'`
	local str=$(date "+%Y-%m-%d %H:%M:%S")" ["$5"/"$6"] "$name"开始安装... "
	echo $(date "+%Y-%m-%d %H:%M:%S")" "$name"开始安装..." >> $installdir/install.log
	arry=("\\" "|" "/" "-")
	while [ true ] 
	do
		status=`curl -s http://$1:$2/mt/api/v1/deployResult/$3/$4`
		if [ -n "$status" ]; then
			case $status in
				1)   
				;;
				2)  echo $str"  "
					echo $(date "+%Y-%m-%d %H:%M:%S")" "$name"安装完成  " 
					echo $(date "+%Y-%m-%d %H:%M:%S")" "$name"安装完成" >> $installdir/install.log
					break
				;;
				3)  echo $str"  "
					echo $(date "+%Y-%m-%d %H:%M:%S")" "$name"安装失败  "
					echo $(date "+%Y-%m-%d %H:%M:%S")" "$name"安装失败" >> $installdir/install.log
					installfail
				;;
				*)
				;;
			esac
		fi
		local i=0
		while [ $i -le 11 ]
		do
			let index=i%4
			printf "%s %c\r" "$str" "${arry[$index]}"
			sleep 0.1
			let i=i+1
		done
	done
	echo 
}
# 等待启动
function validateAppIsrun()
{
	local str=$(date "+%Y-%m-%d %H:%M:%S")" 等待"$2"启动..."
	echo $(date "+%Y-%m-%d %H:%M:%S")" 等待"$2"启动..." >> $installdir/install.log 
	arry=("\\" "|" "/" "-")
	if [ -n "$3" ]; then
		local url="http://"$4":"$5"/login?nextPage=http%3A%2F%2F"$4"%3A"$5"%2Flaunch2%2Fsystem_module%3Fjson%3Dtrue%26app%3D"$3"&user=admin&password=YiShan@700"
		local flag=0
		#let retry=1
		#检查app在luanch2的状态是否为正在运行
		while [ true ] 
		do
			wget -q $url -O testresult.txt
			status=`cat testresult.txt | grep -Po "\"runStatus\"\\s*:\\s*\"\K[^\"]+"`
			if [ -n "$status" ]; then
				case $status in
					"运行正常")  sleep 5
					break
					;;
					"离线")  flag=1
					break
					;;
					"卸载")  flag=1
					break
					;;
					#"停止")  
					#	if [ $retry -eq 0 ];then
					#		flag=1
					#		break
					#	else
					#		retry=retry-1
					#	fi
					#;;
					"重试过多")	flag=1
					break
					;;
					*)
					;;
				esac
			fi
			
			local i=0
			while [ $i -le 11 ]
			do
				let index=i%4
				printf "%s %c\r" "$str" "${arry[$index]}"
				sleep 0.1
				let i=i+1
			done
		done
		if [[ $flag -eq 1 ]]; then
			echo $str"  "
			echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动失败"
			echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动失败，状态为: "$status >> $installdir/install.log
			installfail
		fi
	fi
	#检查app是否已经可以访问
	while [ true ] 
		do
			local httpCode=`curl -L -I -m 10 -o /dev/null -s -w %{http_code} $1`
			if [[ $httpCode -eq 200 ]]; then
				break
			elif [[ "$httpCode" =~ ^50.* ]]; then
				echo $str"  "
				echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动失败"
				echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动失败 "$httpCode >> $installdir/install.log 
				installfail
			fi
			local i=0
			while [ $i -le 11 ]
			do
				let index=i%4
				printf "%s %c\r" "$str" "${arry[$index]}"
				sleep 0.1
				let i=i+1
			done
		done
	echo $str"  "
	echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动正常"
	echo $(date "+%Y-%m-%d %H:%M:%S")" "$2"启动正常" >> $installdir/install.log 
}

cd `dirname $0`
installdir=`pwd`

#加载参数
total=0
acount=0
pcount=0
declare -A param
while read line || [[ -n ${line} ]]
  do
  if [[ -n "$line" && ! "$line" =~ ^\#.* ]]; then
	k=${line%%=*}
	v=${line#*=}
	param[$k]=$v
	#统计需要安装的中台和微应用总数
	if [[ -n "$k" && -n "$v" ]]; then
		if [[ "$k" =~ ^app_.*_serviceId$ ]];then
			total=$(($total + 1))
			acount=$(($acount + 1))
		fi
		if [[ "$k" =~ ^platform_.*_serviceId$ ]];then
			total=$(($total + 1))
			pcount=$(($pcount + 1))
		fi
	fi
  fi
done  < $installdir/install.conf

clear
echo "开始安装${param[product_name]} ${param[product_version]} …"
echo $(date "+%Y-%m-%d %H:%M:%S")" 开始安装${param[product_name]} ${param[product_version]} …" >> $installdir/install.log
echo

#往jetty里面写online文件
> $installdir/base/jetty/beta/etc/online
#base，infra启动
#echo "准备安装base， 正在检查系统配置， 请等待......"
#rm -rf /root/nacos/

#选择服务器ip地址
ipArr=($(/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"))
iplen=${#ipArr[@]}
selectStr=""
for(( i=0;i<$iplen;i++))
do
	ipStr=" "$(($i+1))"、"${ipArr[i]}
	#${#array[@]}获取数组长度用于循环
	if [ $i -lt $(($iplen-1)) ]; then
		ipStr=$ipStr"\n"
	fi
	selectStr=$selectStr" "$ipStr
done;

echo -e "请在下列IP地址中选择产品服务地址：\n"$selectStr
while [ true ]
do
	read -p "请选择序号：" index
	num=`echo $index | sed -e 's/[0-9]$//g'`
	if [[ -z "$num" && $index -ne 0 ]]; then
		index=$(($index-1))
		master_ip=${ipArr[index]}
		echo $(date "+%Y-%m-%d %H:%M:%S")" 选择的ip为："$master_ip >> $installdir/install.log
		if [[ $index -lt $iplen && -n "$master_ip" ]]; then
			break
		fi
	fi
done

#输入节点数量
nodeArr=(${param[node_num]})
nodelen=${#nodeArr[@]}
selectStr=""
for (( i=0;i<$nodelen;i++))
do
	node=${nodeArr[i]}
	nodeStr=" "$(($i+1))"、支持$node节点，要求：CPU至少"${param[cpu_$node]}"C，内存至少"${param[mem_$node]}"G，剩余磁盘至少"${param[storage_$node]}"G"
	if [ $i -lt $(($nodelen-1)) ]; then
		nodeStr=$nodeStr"\n"
	fi
	selectStr=$selectStr" "$nodeStr
done
echo -e "请在下列节点配置中选择：\n"$selectStr

while [ true ]
do
	read -p "请选择序号：" index
	num=`echo $index | sed -e 's/[1-4]$//g'`
	if [[ -z "$num" ]]; then
		index=$(($index-1))
		node=${nodeArr[$index]}
		if [[ $index -lt $nodelen && -n "$node" ]]; then
			if [[ $node -eq 100 ]]; then
				read -p "选择100节点将不包括IP地址簿,日志监控以及数据流相关功能，继续请输入[Y], 重选请输入[N] :" sel
				if [[ "$sel" == "Y" || "$sel" == "y" ]]; then
					break
				fi
			else
				break
			fi
		fi
	fi
done
cpu=${param[cpu_$node]}
mem=${param[mem_$node]}
storage=${param[storage_$node]}
platform_resource_cpu=${param[platform_resource_cpu_$node]}
platform_resource_mem=${param[platform_resource_mem_$node]}
platform_resource_storage=${param[platform_resource_storage_$node]}
app_resource_cpu=${param[app_resource_cpu_$node]}
app_resource_mem=${param[app_resource_mem_$node]}
app_resource_storage=${param[app_resource_storage_$node]}

echo $(date "+%Y-%m-%d %H:%M:%S")" 节点选择为："$node >> $installdir/install.log
echo $(date "+%Y-%m-%d %H:%M:%S")" 节点配置要求{cpu:$cpu  mem:$mem  storage:$storage}" >> $installdir/install.log

product=${param[product_name]}
bt_os_ver="${param[os_version]}"
bt_cpu_count=${cpu}
bt_mem_size=${mem}
bt_disk_size=${storage}
bt_disk_name=${installdir}
bt_disk_bw=${param[disk_bw]}
bt_disk_out=${param[disk_out]}
bt_disk_out_warn=${param[disk_out_warn]}
bt_processes=${param[processes]}
bt_openssl_version=${param[openssl_version]}
#服务器的环境监测以及安全加固
cd $installdir/env
. ./linuxenvcollector.sh
result=`echo $?`

#删除环境检测的测试文件
if [[ -e ${installdir}/test ]];then
	rm -rf ${installdir}/test
fi

if [ $result -ne 0 ]
then
	installfail
fi
cd $installdir

#修改launch2的env.properties文件,将127.0.0.1修改为实际ip地址
sed -i 's/127.0.0.1/'$master_ip'/g' $installdir/launch2/env.properties

user=beta
group=beta

#清除beta group和beta user
sudo userdel -rf $user > /dev/null 2>&1
#sudo groupdel $group

#创建group beta
groupadd $group
#echo $group "用户组创建成功"
echo $(date "+%Y-%m-%d %H:%M:%S")" "$group "用户组创建成功" >> $installdir/install.log
#创建user beta
useradd -g $group $user	
password="YiShan@700"
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
usermod -p $pass $user
#echo $user "用户创建成功"
echo $(date "+%Y-%m-%d %H:%M:%S")" "$user"用户创建成功" >> $installdir/install.log

#自动化部署相关启动程序
#IP设置
cd $installdir/base/goagent

#echo "开始部署"
echo
echo "====================================================="
echo $(date "+%Y-%m-%d %H:%M:%S")" 开始部署base"
echo $(date "+%Y-%m-%d %H:%M:%S")" 开始部署base" >> $installdir/install.log
cd $installdir/base/goagent

mkdir -p $installdir/launch2/etc
cd $installdir/launch2/etc
echo nacos=$master_ip:30000 > nacos.properties
nacosvalue=$(cat nacos.properties)

agent_ip=$master_ip

#增加NTP时间同步机制
if [ "$master_ip" == "$agent_ip" ] 
then
	#IP相同则为infra服务器
	service ntpd stop > /dev/null 2>&1
	sleep 10
	#修改ntp.conf
	cp /etc/ntp.conf /etc/ntp.conf.bak
	sed -i 's/server/#&/' /etc/ntp.conf
	sed -i '/#/'d /etc/ntp.conf
	sed -i '$a\server 127.127.1.0' /etc/ntp.conf
	
	sed -i '/restrict/'d /etc/ntp.conf
	sed -i '$a\restrict 0.0.0.0 mask 0.0.0.0 nomodify notrap' /etc/ntp.conf
	
	sed -i '/fudge/'d /etc/ntp.conf
	sed -i '$a\fudge 127.127.1.0 stratun 10' /etc/ntp.conf
	
	service ntpd start > /dev/null 2>&1
	sleep 10
else
	#IP不同则为base
	service ntpd stop > /dev/null 2>&1
	sleep 10
	ntpdate -u $master_ip
	#增加定时同步任务， 每5分钟同步一次
	echo "ntpdate -u "$master_ip > $installdir/base/timesync.sh
	chmod +x $installdir/base/timesync.sh
	cp /etc/crontab /etc/crontab.bak
	sed -i '/timesync/'d /etc/crontab
	sed -i '$a\*/5 * * * * root '$installdir'/base/timesync.sh' /etc/crontab
	sleep 5
fi

#在launch2/tools目录下配置工具
#清除缓存配置工具， 每天凌晨0点执行，也可以手工执行
chmod +x $installdir/launch2/tools/ClearCache.sh

cp /etc/crontab /etc/crontab.bak
sed -i '/Clear/'d /etc/crontab
sed -i '$a\0 0 * * * root '$installdir'launch2/tools/ClearCache.sh' /etc/crontab
sleep 5

#对installdir目录下的所有sh文件赋可执行权限
cd $installdir
find $installdir -name \*.sh | xargs -r chmod +x

cd $installdir/base/goagent/beta
chmod +x goagent
./goagent set -master $master_ip -agent $agent_ip > /dev/null 2>&1

sed -i -e '/Betasoft/d' /etc/profile
sed -i '$a\export btcloud_home='$installdir /etc/profile
sed -i '$a\export JAVA_HOME='$installdir'/base/jre' /etc/profile
#添加buglet的环境变量配置，防止依赖死循环
sed -i '$a\export BTInfra_T00_S01_btinfra_bugletService_port=30060' /etc/profile
sed -i '$a\export BTInfra_T00_S01_btinfra_bugletService_path=' /etc/profile
sed -i '$a\export BTInfra_T00_S01_btinfra_bugletService_ip='$master_ip /etc/profile
#sed -i '$a\export BTInfra_T00_S01.btinfra_bugletService='$master_ip':30060' /etc/profile
sed -i '$a\export BTInfra_T00_S01_btinfra_bugletService='$master_ip':30060' /etc/profile

echo $master_ip > $installdir/base/master_ip

sleep 5

cd $installdir/base/jre
chmod -R +x bin/

cd $installdir/base/pgsql
chmod -R +x bin/

#base安装完成之后执行脚本
source $installdir/base/init_base.sh

echo $(date "+%Y-%m-%d %H:%M:%S")" base部署完成"
echo $(date "+%Y-%m-%d %H:%M:%S")" base部署完成" >> $installdir/install.log
echo

#对installdir目录下的所有sh文件赋可执行权限
echo $(date "+%Y-%m-%d %H:%M:%S")" 开始部署infra"
echo $(date "+%Y-%m-%d %H:%M:%S")" 开始部署infra" >> $installdir/install.log
cd $installdir
find $installdir -name \*.sh | xargs -r chmod +x

cd $installdir/infra/rabbitmq/
chmod -R +x erl/
chmod -R +x rabbitmq_server/

cd $installdir/infra/redis
chmod -R +x bin/

cd $installdir/infra/nginx/beta
chmod -R +x bin/

cd $installdir/infra/nginx/beta
chmod -R +x bin/
chmod -R +x nginx

cd $installdir/infra/gomaster/beta
chmod -R +x gomaster

source /etc/profile
cd $installdir/launch2
./install.sh

echo $(date "+%Y-%m-%d %H:%M:%S")" infra部署完成"
echo $(date "+%Y-%m-%d %H:%M:%S")" infra部署完成" >> $installdir/install.log

#关闭防火墙
service firewalld stop > /dev/null 2>&1
systemctl disable firewalld.service > /dev/null 2>&1
cd $installdir

ip=$master_ip
port=${param[mt_port]}
launch2Port=${param[launch2_port]}

echo "====================================================="
#检测launch2是否启动
url="http://${ip}:${launch2Port}/login?nextPage=http%3A%2F%2F${ip}%3A${launch2Port}%2Flaunch2%2Fsystem_module%3Fjson%3Dtrue%26app%3Dbtinfra_soc&user=admin&password=YiShan@700"
validateAppIsrun $url "launch2"

echo
#检测mt是否启动正常
url=http://${ip}:${port}/mt/login
validateAppIsrun $url "运营中心" "btinfra_soc" $ip $launch2Port

#写入环境变量
#sed -i '$a\export BETA_PRODUCT_SPECIFICATION='$node /etc/profile
setEnvUrl=http://${ip}:${port}/mt/api/v1/set/product/env
env_data='{"BETA_PRODUCT_SPECIFICATION":"'$node'"}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${env_data}" ${setEnvUrl}`
validateResult "$result" "设置产品规格"
echo $(date "+%Y-%m-%d %H:%M:%S")" 产品节点数规格为"$node >> $installdir/install.log

#创建标识文件
touch ${installdir}/infra/deployplan/beta/setup

#添加资源 post
addResourceUrl=http://${ip}:${port}/mt/api/v1/resource/saveOrUpdate
resource_ip=$master_ip
# 中台使用的资源
resource_data='{"ip": "'${resource_ip}'", "node": "'${param[resource_platform_node]}'", "location": "'${param[resource_location]}'", "cpu": "'${platform_resource_cpu}'", "mem": "'${platform_resource_mem}'", "storage": "'${platform_resource_storage}'", "system": "'${param[resource_system]}'", "depict": "'${param[resource_depict]}'"}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${resource_data}" ${addResourceUrl}`
validateResult "$result" "ADD PLATFORM RESOURCE"
# 应用使用的资源
resource_data='{"ip": "'${resource_ip}'", "node": "'${param[resource_app_node]}'", "location": "'${param[resource_location]}'", "cpu": "'${app_resource_cpu}'", "mem": "'${app_resource_mem}'", "storage": "'${app_resource_storage}'", "system": "'${param[resource_system]}'", "depict": "'${param[resource_depict]}'"}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${resource_data}" ${addResourceUrl}`
validateResult "$result" "ADD APP RESOURCE"

#获取中台资源id get
getResourceUrl=http://${ip}:${port}/mt/api/v1/resource/${resource_ip}/${param[resource_platform_node]}
platform_resourceId=`curl -s "${getResourceUrl}" | grep -Po "\"id\"\\s*:\\s*\K[\\d]+"`
echo $(date "+%Y-%m-%d %H:%M:%S")" 获取到的中台资源id为：$platform_resourceId" >> $installdir/install.log

echo "====================================================="
echo "开始安装中台"
echo
#安装中台 post 
installPlatFormUrl=http://${ip}:${port}/mt/api/v1/deploy/platform/install/${platform_resourceId}
#安装文件install.conf中的中台应用
btpmServiceId=""
installCount=0
while read line || [[ -n ${line} ]]
  do
	k=${line%=*}
	v=${line#*=}
	if [[ -n "$k" && -n "$v" && "$k" =~ ^platform_.*_serviceId$ ]]; then
		name=`echo $v | awk -F "_" '{print $1}'`
		#echo $(date "+%Y-%m-%d %H:%M:%S")" 开始下发"$name"安装计划" >> $installdir/install.log
		platform_data=''
		#判断是否为dgo_engine，需要采集器名称和备注
		if [[ $k =~ dgoEngine_.* ]]
		then
			platform_data='[{"name": "中台", "serviceId": "'$v'", "action": "'${param[action]}'", "alias": "'${param[dgo_engine_alias]}'", "remark": "'${param[dgo_engine_remark]}'"}]'
		else
			platform_data='[{"name": "中台", "serviceId": "'$v'", "action": "'${param[action]}'"}]'
		fi
		result=`curl -s -X POST -H "Content-type:application/json" -d "${platform_data}" ${installPlatFormUrl}`
		validateResult "$result" "下发"$name"安装计划"
		installCount=$(($installCount + 1))
		validateAppInstall $ip $port $platform_resourceId $v $installCount $total
		#判断是否为btpm，保存serviceId
		if [[ $k =~ btpm_.* ]]; then
			btpmServiceId=$v
		fi
	fi
done  < $installdir/install.conf
echo "中台全部安装完成"

#创建域管理员 post
addRegionUrl=http://${ip}:${port}/mt/api/v1/region/saveOrUpdate
region_data='{"regionName": "'${param[region_name]}'", "cpu": "'${param[region_cpu]}'", "mem": "'${param[region_mem]}'", "storage": "'${param[region_storage]}'", "comment": "'${param[region_comment]}'", "userEntityList": [{ "userName": "'${param[region_user_name]}'", "passWord": "'${param[region_user_pwd]}'"}]}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${region_data}" ${addRegionUrl}`
validateResult "$result" "CREATE REGION ADMINISTRATOR"

#租户申请 post
applyTenantUrl=http://${ip}:${port}/mt/api/v1/tenant/apply
applyTenant_data='{"regionName": "'${param[region_name]}'", "tenantName": "'${param[tenant_name]}'", "cpu": "'${param[tenant_cpu]}'", "mem": "'${param[tenant_mem]}'", "storage": "'${param[tenant_storage]}'", "remark": "'${param[tenant_remark]}'"}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${applyTenant_data}" ${applyTenantUrl}`
echo $(date "+%Y-%m-%d %H:%M:%S") "APPLY TENANT result:"$result >> $installdir/install.log
applyResult=`echo $result | grep -Po "\"applyResult\"\\s*:\\s*\"\K[^\"]+"`
if [ "FAILURE" == "$applyResult" ]
then
	failReason=`echo $result | grep -Po "\"failReason\"\\s*:\\s*\"\K[^\"]+"`
	echo $(date "+%Y-%m-%d %H:%M:%S") " APPLY TENANT FAILURE！${failReason}" >> $installdir/install.log
	installfail
else
	echo $(date "+%Y-%m-%d %H:%M:%S") " APPLY TENANT SUCCESS！${failReason}" >> $installdir/install.log
fi
tenantNumber=`echo $result | grep -Po "\"tenantNumber\"\\s*:\\s*\"\K[^\"]+"`
echo $(date "+%Y-%m-%d %H:%M:%S") " 获取的租户编号: $tenantNumber" >> $installdir/install.log

if [ -z "$tenantNumber" ]; then
	installfail
fi

#获取租户id get
getTenantUrl=http://${ip}:${port}/mt/api/v1/tenant/number/${tenantNumber}
tenantId=`curl -s ${getTenantUrl} | grep -Po "\"id\"\\s*:\\s*\K[\\d]+"`
echo  $(date "+%Y-%m-%d %H:%M:%S") " 获取到的租户ID为：$tenantId" >> $installdir/install.log

#租户审核 put
auditTenantUrl=http://${ip}:${port}/mt/api/v1/tenant/${tenantId}/audit/1
auditTenant_data='{"tenantId": "'${tenantId}'", "tenantName": "'${param[tenant_name]}'", "cpu": "'${param[tenant_cpu]}'", "mem": "'${param[tenant_mem]}'", "storage": "'${param[tenant_storage]}'", "remark": "'${param[tenant_remark]}'", "recoveryDate": '${param[tenant_recoveryDate]}'}'
result=`curl -s -X PUT -H "Content-type:application/json" -d "${auditTenant_data}" ${auditTenantUrl}`
validateResult "$result" "AUDIT TENANT"

#获取应用资源id get
getAppResourceUrl=http://${ip}:${port}/mt/api/v1/resource/${resource_ip}/${param[resource_app_node]}
app_resourceId=`curl -s "${getAppResourceUrl}" | grep -Po "\"id\"\\s*:\\s*\K[\\d]+"`
echo $(date "+%Y-%m-%d %H:%M:%S") " 安装app的资源id：$app_resourceId" >> $installdir/install.log

#分配资源 put
allocatResourceUrl=http://${ip}:${port}/mt/api/v1/tenant/${tenantId}/resource/${app_resourceId}/allocation
result=`curl -s -X PUT ${allocatResourceUrl}`
validateResult "$result" "ALLOCATION RESOURCE"

if [[ -z "$btpmServiceId" ]]; then
	echo $(date "+%Y-%m-%d %H:%M:%S")" 检测到未安装btpm中台，无法创建mo权限规则，所以无法安装微应用，安装终止" >> $installdir/install.log
	installfail
fi
#获取BTPM的铭牌
getNameplateUrl=http://${ip}:${port}/mt/api/v1/application/${platform_resourceId}/${btpmServiceId}
result=`curl -s ${getNameplateUrl}`
nameplate=`echo ${result} | grep -Po "\"nameplate\"\\s*:\\s*\"\K[^\"]+"`
platformId=`echo ${result} | grep -Po "\"id\"\\s*:\\s*\K[\\d]+"`
echo $(date "+%Y-%m-%d %H:%M:%S")" 获取到的btpm中台铭牌为："$nameplate",中台id为："$platformId >> $installdir/install.log

#检测BTPM是否正常启动，超时时间30s
echo "====================================================="
btpm_port=${param[btpm_port]}
url=http://${ip}:${btpm_port}/moc
validateAppIsrun $url "btpm中台" $nameplate $ip $launch2Port

#创建租户的mo权限规则，不然无法安装app
saveAuthorityUrl=http://${ip}:${port}/mt/api/v1/authority/save/${param[region_name]}
authority_data='{"authorityType": '${param[authority_type]}', "ip": "'${param[authority_ip]}'", "excludeIp": "'${param[authority_excludeIp]}'","moType": "'${param[authority_moType]}'","pdmEngine": "'${param[authority_pdmEngine]}'","ruleName": "'${param[authority_ruleName]}'","nameplate": "'${nameplate}'","platformId": "'${platformId}'","tenantNumber": "'${tenantNumber}'","ruleId": ""}'
result=`curl -s -X POST -H "Content-type:application/json" -d "${authority_data}" ${saveAuthorityUrl}`
validateResult "$result" "SAVE AUTHORITY"
echo "====================================================="

if [[ $acount -gt 0 ]]; then
	echo "开始安装微应用"
	echo
	#安装app post
	installAppUrl=http://${ip}:${port}/mt/api/v1/deploy/app/${app_resourceId}/${tenantId}
	#安装文件install.conf中的微应用
	while read line || [[ -n ${line} ]]
	  do
		k=${line%=*}
		v=${line#*=}
		if [[ -n "$k" && -n "$v" && "$k" =~ ^app_.*_serviceId$ ]]; then
			name=`echo $v | awk -F "_" '{print $1}'`
			app_data='[{"name": "应用", "serviceId": "'$v'", "action": "'${param[action]}'"}]'
			result=`curl -s -X POST -H "Content-type:application/json" -d "${app_data}" ${installAppUrl}`
			validateResult "$result" "下发"$name"安装计划"
			installCount=$(($installCount + 1))
			validateAppInstall $ip $port $app_resourceId $v $installCount $total
		fi
	done  < $installdir/install.conf
	echo "微应用全部安装完成"
	
	url="http://"$ip
	#安装完成后，等待服务启动
	validateAppIsrun $url "服务"
	
	echo "====================================================="
	echo 

	echo ${param[product_name]}"已成功安装，请访问 "${url}" 默认账号为"${param[username]}"，密码为"${param[password]}
	echo $(date "+%Y-%m-%d %H:%M:%S")" "${param[product_name]}"已成功安装，请访问 "${url}" 默认账号为"${param[username]}"，密码为"${param[password]} >> $installdir/install.log
else
	echo ${param[product_name]}"已成功安装!"
	echo $(date "+%Y-%m-%d %H:%M:%S")" "${param[product_name]}"已成功安装!" >> $installdir/install.log
fi

cd $installdir
rm -f testresult.txt
rm -f ${installdir}/infra/deployplan/beta/setup

#清除buglet的环境变量配置
sed -i '/export BTInfra_T00_S01_btinfra_bugletService_port=30060/d' /etc/profile
sed -i '/export BTInfra_T00_S01_btinfra_bugletService_path=/d' /etc/profile
sed -i '/export BTInfra_T00_S01_btinfra_bugletService_ip='$master_ip'/d' /etc/profile
#sed -i '/export BTInfra_T00_S01.btinfra_bugletService='$master_ip':30060/d' /etc/profile
sed -i '/export BTInfra_T00_S01_btinfra_bugletService='$master_ip':30060/d' /etc/profile

#systemctl set-default multi-user.target > /dev/null 2>&1

systemctl start firewalld > /dev/null 2>&1
echo
echo "为保证系统安全，已开启防火墙！"
echo
